package com.lance.answer.question_answer.xj_new;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.lance.answer.dto.CompleteInfo;
import com.lance.answer.dto.CourseInfo;
import com.lance.answer.dto.XjUserCourseInfo;
import com.lance.answer.gui.answer.AnswerObject;
import com.lance.answer.gui.answer.DealJsonString;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.util.Constant;
import com.lance.answer.util.HttpUtil;
import com.lance.answer.util.XinJiangUtil;
import com.lance.answer.util.image_valid.VerifyCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * @author fengx
 * 新疆一体化答题-考试    ----------迪尼达·马合木提
 *
 * </p>
 */

@Slf4j
public class BatchDoXJAnswerTesting {




    private static List<WebElement> findWeElements(WebDriver driver, String cssSelector, int second) {
        return (new WebDriverWait(driver, Duration.ofSeconds(second))).until((ExpectedCondition<List<WebElement>>) d -> {
            assert d != null;
            return d.findElements(By.cssSelector(cssSelector));
        });
    }


    public static void main(String[] args) throws IOException {

        List<String> vip = Lists.newArrayList(
                "653221200108020023",
                "650104198411090732",
                "654101200103133221",
                "653123200105180029",
                "653129200201012103",
                "653022200206090821",
                "653101200206233224",
                "653129200106221724",
                "652123200005101548",
                "653101200209104882",
                "653126200101013505",
                "653021199912060425",
                "65312620010904084X",
                "654202199610226314",
                "65422219971115321X",
                "513902198505077187"
        );

        // 校验是否提交
        int sync = 16 ;


        //预加载所有用户信息
        InputStream inputStream3 = new FileInputStream("E:\\alluser.txt");
    //    InputStream inputStream3 = new FileInputStream("E:\\一体化2022.user");
        List<String> allUsers = IOUtils.readLines(inputStream3, "utf-8");
        Map<String, String> usernameAndPwd = Maps.newHashMap();

        for (String user : allUsers) {
            String[] strs = user.split(",");
            String userCode = strs[0];
            String pwd = strs[1];
            if (pwd.length() > 14) {
                if (pwd.contains("X")) {
                    pwd = userCode.substring(11, 17);
                } else {
                    pwd = userCode.substring(12);
                }
            }
          //  usernameAndPwd.put(userCode.toUpperCase(Locale.ROOT), pwd);
            usernameAndPwd.put(userCode, pwd);
        }


        InputStream inputStream = new FileInputStream("E:\\排名map.txt");
        List<String> allKeyValues = IOUtils.readLines(inputStream, "utf-8");
        Map<String, String> mapTmp = Maps.newHashMap();
        for (String keyValues : allKeyValues) {
            String[] strs = keyValues.split("&");
            String k1 = strs[0];
            String v1 = strs[1];
            mapTmp.put(k1, v1);
        }

        //加载所有课程配置
        List<CourseInfo> courseList = Lists.newArrayList();
        for (File file : new File("D:\\新疆一体化测验作业").listFiles()) {

           try {
               if(file.listFiles()[0].length()<1000){
                   continue;
               }
           }catch (Exception e){

           }

            String code = file.getName();
            CourseInfo courseInfo = new CourseInfo();
            courseInfo.setOpenCourseId(Integer.parseInt(code));
            courseInfo.setSubjectName(mapTmp.get(code));
            courseList.add(courseInfo);
            //Constant.COURSE_QUEUE.addLast(new CourseInfo(Integer.parseInt(code), mapTmp.get(code)));
        }
        Collections.sort(courseList);


        // 加载每个课程答案
        for (CourseInfo info : courseList) {
            //获取模板路径,通过流的方式获取文件可以避免被打成jar包之后无法获取文件路径的异常
            String subjectName = info.getSubjectName();
            if(Strings.isNullOrEmpty(subjectName)){
                continue;
            }
            subjectName = subjectName.trim();
            int  openCourseId = info.getOpenCourseId();
            InputStream inputStream1 = new FileInputStream("D:\\新疆一体化测验作业\\" + openCourseId + "\\" + subjectName + "（测验作业）.json");
            String answerStr = IOUtils.toString(inputStream1, StandardCharsets.UTF_8);
            List<AnswerObject> listAnswerObject = JSONObject.parseArray(answerStr, AnswerObject.class);
            Map<String, AnswerObject> answerMap = Maps.newHashMap();
            for (AnswerObject answerObject : listAnswerObject) {
                answerMap.put(DealJsonString.delHTMLTag(Util.dealContent(answerObject.getQuestionTitle())), answerObject);
            }
            info.setAnswerMap(answerMap);
        }


        int count = 1000;

        // 加载用户答题参数
        LinkedBlockingDeque<CourseInfo> userCourseQueue = new LinkedBlockingDeque<>();
        for (CourseInfo courseInfo : courseList) {
//
//            if(count<0){
//                break;
//            }
//            count--;

            int  openCourseId = courseInfo.getOpenCourseId();
            // 职业给
//            if(openCourseId==30944||openCourseId ==31126 ||openCourseId == 33355
//                    ||openCourseId == 33544 ||openCourseId == 32013||openCourseId == 31941 ||openCourseId ==32774
//                    ||openCourseId ==32958
//                    // 宪法学 TODO
//                    ||openCourseId ==38931
//                    // 形势与政策 TODO
//                    ||openCourseId ==38903
//                    // 汉语综合技能 TODO
//               //     ||openCourseId ==39128
//            ){
//                continue;
//            }
            if(
                    // 宪法学 TODO
                //    openCourseId ==38931
                    openCourseId ==33969 //  工具书与文献检索
        //  ||  openCourseId ==38903 // 形势与政策 TODO
       //   ||  openCourseId ==38419 // 社会保障学
    //      ||  openCourseId ==36246 // 语言文字法规 (51070) 系统异常做不了 TODO
                // 汉语综合技能 TODO
                //     ||openCourseId ==39128
            ){
                continue;
            }



            // 31126
            File jsonFile = new File("E:\\XjStudentCourseInfoTmp\\names\\" + courseInfo.getOpenCourseId() + ".json");
            if(!jsonFile.exists()){
                continue;
            }
            InputStream inputStream4 = new FileInputStream(jsonFile);
            String userStr = IOUtils.toString(inputStream4, StandardCharsets.UTF_8);
            // 当前这门课程所有的
            List<String> users = JSONObject.parseArray(userStr, String.class);
            for (String s : users) {
                String pwd = usernameAndPwd.get(s.toUpperCase(Locale.ROOT));
                CourseInfo courseInfo1 = new CourseInfo();
                courseInfo1.setAnswerMap(courseInfo.getAnswerMap());
                courseInfo1.setOpenCourseId(courseInfo.getOpenCourseId());
                courseInfo1.setSubjectName(courseInfo.getSubjectName());
                courseInfo1.setPwd(pwd);
                courseInfo1.setUser(s);
//                if(!s.equals("411024200002166237")){
//                    continue;
//                }

//                if("65412619990824051X".equals(s)){
//                    continue;
//                }

//                if(!vip.contains(s)){
//                    continue;
//                }
                userCourseQueue.addLast(courseInfo1);
            }
        }






        for (int i = 1; i <= sync; i++) {
            Thread answerThread = new BatchDoXJAnswerTestingTask("d:\\ynouAutoStudy\\chromedriver.exe",userCourseQueue);
            //log.info("加载课程ID：{} 名称：{} ", openCourseId,subjectName);
            answerThread.setName( "答题线程--" + i);
            answerThread.start();
        }



    }







}
